﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

public partial class XSocketClient
{
    class StateObject
    {
        public const int BufferSize = 4096;
        internal byte[] buffer = new byte[BufferSize];
    }
    private StateObject _stateObject = new StateObject();
    private XStreamParser _parser;

    private void Receive()
    {
        _socket.BeginReceive(_stateObject.buffer, 0, _stateObject.buffer.Length, SocketFlags.None, OnReceive, _stateObject);
    }

    private void OnReceive(IAsyncResult asyncReceive)
    {
        var socket = _socket;
        var stateObject = asyncReceive.AsyncState as StateObject;
        try
        {
            int length = socket.EndReceive(asyncReceive);
            if (length > 0)
            {

                _parser.ProcessBytes(stateObject.buffer, 0, length);
                Receive();
            }
            else
            {
                NetWorkChanged(NetWorkState.Disconnected, "OnReceive收到0包长，一般都是服务端主动断socket");
            }
        }
        catch (SocketException e)
        {
            NetWorkChanged(NetWorkState.Disconnected, "Receive:" + e.Message);
        }
    }

}
